from flask import request,Blueprint,jsonify
import requests
import sys, os
sys.path.append("../")
from whoosh.index import create_in, open_dir
from whoosh.fields import *
from whoosh.qparser import QueryParser
from whoosh.highlight import Highlighter
from whoosh.highlight import HtmlFormatter
from jieba.analyse.analyzer import ChineseAnalyzer
from whoosh.filedb.filestore import FileStorage
analyze = Blueprint('analyze', __name__)
# 导入中文分词工具
analyzer = ChineseAnalyzer()
# 创建搜索引擎
schema = Schema(score=TEXT(stored=True), url=ID(stored=True), content=TEXT(stored=True,chars=True, analyzer=analyzer))
if not os.path.exists("tmp"):
    os.mkdir("tmp")
ix = create_in("tmp", schema=schema, indexname='indexname')
def createIndex(dataList):
    # temp 为索引创建的地址，indexname为索引名称
    # ix = open_dir("tmp") # for read only
    storage = FileStorage("tmp")
    ix=storage.open_index(indexname="indexname")
    writer = ix.writer()
    for item in dataList:
        # 添加内容，类似于引擎搜索的库
        writer.add_document(
            score=item.score,
            url=item.url,
            content=item.content
        )
    print("添加内容完毕")
    writer.commit()

@analyze.route("/searchByContent")
def searchByContent():
    keyword=request.args.get("keyword")
    # temp 为索引创建的地址，indexname为索引名称
    storage = FileStorage("tmp")
    ix = storage.open_index(indexname="indexname")
    writer = ix.writer()
    ################ 以上为建立索引的过程 ##############
    searcher = ix.searcher()
    parser = QueryParser("content", schema=ix.schema)
    q = parser.parse(keyword)  # 搜索的关键字
    results = searcher.search(q)
    formatter =  HtmlFormatter(tagname="font",classname="",termclass="",attrquote="")
    idefineHighlighter=Highlighter(formatter=formatter)
    list=[]
    for hit in results:
        highContent=idefineHighlighter.highlight_hit(hit, fieldname="content")
        dict={
            "content":highContent,
            "url":hit.get("url"),
            "score":hit.get("score")
        }
        list.append(dict)
        print(hit.highlights("content"))
        print(hit.get("url"))
        print(hit.get("score"))
        print(highContent)
    #关闭writer
    writer.cancel()
    #返回得数据要求格式
    resp={
        "code":0,
        "msg":"",
        "data":list,
        "count":list.__len__()
    }
    return jsonify(resp)
